// pages/second_detail/second_detail.js
const QQMapWX = require('../../api/qqmap-wx-jssdk.min.js');
const qqmapsdk = new QQMapWX({
  key: '57FBZ-3D6KV-E2HPB-5PYWU-YKQIQ-CMFSZ' // 在腾讯地图开放平台申请得到的key
});

Page({

  /**
   * 页面的初始数据
   */
  data: {
    data:"",
    latitude: "",
    longitude: "",
    accuracy: "",
    searchPlace:"",
    nearbyMerchants: [],
    my_latitude:"",
    my_longitude:"",
    chooseAddress:"",
  },

  chooseAddressFn(){
    let that=this
    wx.chooseLocation({
      latitude: that.data.latitude,
      longitude: that.data.longitude,
      success(e){
        console.log(e)
        that.setData({
          chooseAddress:e.address+e.name, //具体详细信息需另外填写（门牌号等）
          my_latitude: e.latitude,
          my_longitude: e.longitude,
        });
      }
    })
  },
  //获取当前位置信息，获得lat,lng国测局坐标系
  getMyLocation(){
    wx.getLocation({
        type: 'gcj02',
        isHighAccuracy:true,//高精度
        success (res) {
          that.setData({
            my_latitude:res.latitude,
            my_longitude:res.longitude
          })
          const speed = res.speed
          const accuracy = res.accuracy
          qqmapsdk = new QQMapWX({
            key: '57FBZ-3D6KV-E2HPB-5PYWU-YKQIQ-CMFSZ'
          });
          //根据经纬度逆解析成地址
          qqmapsdk.reverseGeocoder({
            location: {
              latitude: res.latitude,
              longitude: res.longitude
            },
            success: function (res) {
              console.log(res);
              var add = res.result.address;
              that.setData({
                chooseAddress: add //具体详细信息需另外填写（门牌号等）
              })
            },
            fail: function (res) {
              console.log(res);
            },
          })
        }
     })
    },

    backfill: function (e) {
      var id = e.currentTarget.id;
      console.log(id)
      for (var i = 0; i < this.data.suggestion.length;i++){
        if(i == id){
          this.setData({
            backfill: this.data.suggestion[i].title
          });
        }  
      }
    },
   
  //触发关键词输入提示事件
  getsuggest: function(e) {
      var _this = this;
      //调用关键词提示接口
      qqmapsdk.getSuggestion({
        //获取输入框值并设置keyword参数
        keyword: e.detail.value, //用户输入的关键词，可设置固定值,如keyword:'KFC'
        region:"上海",
        //region:'北京', //设置城市名，限制关键词所示的地域范围，非必填参数
        success: function(res) {//搜索成功后的回调
          console.log(res);
          var sug = [];
          for (var i = 0; i < res.data.length; i++) {
            sug.push({ // 获取返回结果，放到sug数组中
              title: res.data[i].title,
              id: res.data[i].id,
              addr: res.data[i].address,
              city: res.data[i].city,
              district: res.data[i].district,
              latitude: res.data[i].location.lat,
              longitude: res.data[i].location.lng
            });
          }
          _this.setData({ //设置suggestion属性，将关键词搜索结果以列表形式展示
            suggestion: sug
          });
        },
        fail: function(error) {
          console.error(error);
        },
        complete: function(res) {
          console.log(res);
        }
      });
  },

  search(res){
    qqmapsdk.geocoder({
      address: this.data.searchPlace,
      success:(res)=>{
        let destLatitude = res.result.location.lat // 目的地纬度
        let destLongitude = res.result.location.lng // 目的地经度
    
        // 计算距离
        qqmapsdk.calculateDistance({
          from: {//开始地点
            latitude:this.data.latitude,
            longitude:this.data.longitude
          },
          to: [{//结束地点
            latitude: destLatitude,
            longitude: destLongitude
          }],
          success:(res)=>{
            wx.showToast({
              image:'/images/定位 (1).png',
              title: '距离为：' + res.result.elements[0].distance,
            })
          }
      })
    }
    })
  },

  searchPlace(res){
    this.setData({
      searchPlace:res.detail.value
    })
  },

  message(res){
    let id = res.currentTarget.dataset.id
    wx.redirectTo({
      url: '/pages/second_message/second_message?id='+id
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getMyLocation
    wx.getLocation({
      type: 'wgs84',
      success:(res)=>{
        this.setData({
          latitude:res.latitude, // 纬度
          longitude:res.longitude // 经度
        })
        console.log(this.data.latitude)
        console.log(this.data.longitude)
      }
    })
    let id = options.id
    wx.request({
      url: 'http://www.house.com/api/wzm/second_hand_house_detail/'+id,
      success:(res)=>{
        this.setData({
          data:res.data.data
        })
      }
    })
    wx.getLocation({
      isHighAccuracy: true, 
      type: 'gcj02',
      success: (res) => {
        this.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          marker: [{
            id:1,
            latitude: res.latitude,
            longitude: res.longitude,
            iconPath: '/images/定位.png',
            width: '100rpx',
            height: '100rpx'
          }
          ]
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.mapCtx = wx.createMapContext('myMap')
    this.getMapCenterLocation()
  },

  getMapCenterLocation() {
    const that = this
    this.mapCtx.getCenterLocation({
      success: function(res) {
        console.log(res.longitude)
        console.log(res.latitude)

        // 在此处将用户位置信息发送到后端服务器获取周围商家信息
        wx.request({
          url: 'https://example.com/nearby',
          method: 'GET',
          data: {
            longitude: res.longitude,
            latitude: res.latitude
          },
          success(res) {
            that.setData({
              nearbyMerchants: res.data.merchants
            })
            // 在地图上展示附近的商家标注
            that.showMarkers(res.data.merchants)
          }
        })
      }
    })
  },

  showMarkers(merchants) {
    const markers = merchants.map((merchant) => ({
      id: merchant.id,
      longitude: merchant.longitude,
      latitude: merchant.latitude,
      iconPath: '/images/定位 (1).png',
      width: 20,
      height: 20
    }))
    this.setData({
      markers: markers
    })
  },

  onRegionChange: function(e) {
    if (e.type === 'end') {
      this.getMapCenterLocation()
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})